package app
{
    import app.configuration.NodeFileMeta;
    import app.debug.APPLog;
    import app.displayTree.DisplayTreeBuildManger;

    import copyengine.utils.GeneralUtils;

    import flash.display.Loader;
    import flash.display.LoaderInfo;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.filesystem.File;
    import flash.net.URLRequest;
    import flash.system.System;

    /**
     * 每个SWF文件分析的入口类
     * 1·加载每个SWF文件
     * 2·分析
     * 3·卸载
     */
    public final class SWFInfoTreeEntry
    {
        private var mLoader:Loader;
        private var mNodeConfigFile:NodeFileMeta;
        private var mFinishCallback:Function;

        private var displayTreeBuildManger:DisplayTreeBuildManger;


        public function SWFInfoTreeEntry()
        {
        }

        public function analyzeSWFFile(_nodeConfigFile:NodeFileMeta, _finishCallback:Function):void
        {
            mNodeConfigFile = _nodeConfigFile;
            mFinishCallback = _finishCallback;

            mLoader = new Loader();
            //必须使用URL加载,否则在Mac下面无法正常加载SWF文件
            mLoader.load(new URLRequest(new File(mNodeConfigFile.inputFile).url));
            GeneralUtils.addTargetEventListener(mLoader.contentLoaderInfo, Event.COMPLETE, onFileLoadComplete);
            GeneralUtils.addTargetEventListener(mLoader.contentLoaderInfo, IOErrorEvent.IO_ERROR, onFileLoadError);
        }

        private function onFileLoadComplete(e:Event):void
        {
            var loaderInfo:LoaderInfo = e.currentTarget as LoaderInfo;

            APPLog.log("Start analyze file");
            displayTreeBuildManger = new DisplayTreeBuildManger();
            displayTreeBuildManger.prepare(loaderInfo.applicationDomain);
            displayTreeBuildManger.startAnalyzeFile(mNodeConfigFile);
            APPLog.log("End analyze file");


            mLoader.unloadAndStop();
            mLoader = null;
            System.gc();
            System.gc();
            mNodeConfigFile.isAnyliseFinish = true;
            mFinishCallback();
        }

        private function onFileLoadError(e:Event):void
        {
            APPLog.err(e.toString());
            APPLog.log("Can not load file : " + mNodeConfigFile.fileName);
        }

    }
}
